#!/bin/sh
# Job yaml can send below ENVIRONMENT VARIABLES to me
# - cg_count
# - cg_bind
# - group
# - cpu.cfs_period_us
# - cpu.cfs_quota_us
# - cpu.rt_period_us
# - cpu.rt_runtime_us
# - cpuset.cpu_exclusive
# - cpuset.cpus
# - cpuset.mem_exclusive
# - cpuset.mem_hardwall
# - cpuset.memory_migrate
# - cpuset.memory_pressure
# - cpuset.memory_pressure_enabled
# - cpuset.memory_spread_page
# - cpuset.memory_spread_slab
# - cpuset.mems
# - cpuset.sched_load_balance
# - cpuset.sched_relax_domain_level
# - memory.kmem.limit_in_bytes
# - memory.kmem.tcp.limit_in_bytes
# - memory.limit_in_bytes
# - memory.memsw.limit_in_bytes
# - memory.move_charge_at_immigrate
# - memory.oom_control
# - memory.soft_limit_in_bytes
# - memory.swappiness
# - memory.use_hierarchy
# - blkio.weight
# - blkio.weight_device
# - blkio.throttle.read_bps_device
# - blkio.throttle.write_bps_device
# - blkio.throttle.read_iops_device
# - blkio.throttle.write_iops_device
# END ENVIRONMENT VARIABLES

. $LKP_SRC/lib/common.sh
. $LKP_SRC/lib/reproduce-log.sh
. $LKP_SRC/lib/debug.sh
. $LKP_SRC/lib/cgroup.sh

CGROUP_MNT=/cgroup

[ -e '/proc/cgroups' ] || die "dir not exist: /proc/cgroups"

: "${cg_count:=1}"

if [ -z "$cg_bind" ] && [ "$cg_count" -eq 1 ]; then
	cg_bind=1
fi

# Clear cgroups and subsystem controllers mount point for v1 version
clear_cgroup

#clear cgroups and subsystem controllers mount point for v2 version
clear_cgroup2

create_one_cgroup()
{
	cgname=$1
	#Bind each subsystem to an individual hierachy and create an individual control group
	create_cgroup "$CGROUP_MNT" "$cgname"

	#Tuning parammeter defined in the jobfile
	env | grep -F '_46_' |
	while read line
	do
		key=${line%%=*}
		val=${line##*=}
		[ -n "$val" ] || continue
		param=$(echo "$key" | sed 's/_46_/./g')
		if [ "${key%%_46_*}" = "cpu" -o "${key%%_46_*}" = "cpuacct" ]; then
			if [ -w "$CGROUP_MNT/cpu,cpuacct/$cgname/$param" ]; then
				log_eval "echo '$val' > '$CGROUP_MNT/cpu,cpuacct/$cgname/$param'"
			else
				echo "Warning: parammeter $param doesn't exist or doesn't have write \
permission in $CGROUP_MNT/cpu,cpuacct/$cgname/ directory"
			fi

		elif [ -w "$CGROUP_MNT/${key%%_46_*}/$cgname/$param" ]; then
			log_eval "echo '$val' > '$CGROUP_MNT/${key%%_46_*}/$cgname/$param'"
		else
			echo "Warning: parammeter $param doesn't exist or doesn't have write \
permission in $CGROUP_MNT/${key%%_46_*}/$cgname/ directory"
		fi
	done
}

for i in $(seq 1 "$cg_count"); do
	name="$testcase.$i"
	create_one_cgroup "$name"
	cgroup_names="$cgroup_names $name"
done

if parse_bool -q "$cg_bind"; then
	#Set PPID to first cgroup tasks
	for subsys_tasks in $CGROUP_MNT/*/$testcase.1/tasks; do
		log_eval "echo '$PPID' > '$subsys_tasks'"
	done
fi

cat >> $TMP/env.yaml <<EOF

# setup/cgroup
CGROUP_MNT: $CGROUP_MNT
cgroup_ver: 1
cgroups: $cgroup_names
EOF
